package com.vcredit.creditcat.web.api.product;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.api.product.h5.IRepaymentCallbackManager;
import com.vcredit.creditcat.dto.product.h5.RepaymentplainDto;
import com.vcredit.creditcat.dto.product.h5.RepaymentplainItemDto;
import com.vcredit.creditcat.utils.CommonSecuritUtil;
import com.vcredit.creditcat.vo.CommonProductCreditCallbackParam;
import com.vcredit.creditcat.vo.CommonResultVo;
import com.vcredit.creditcat.vo.payday.CommonRequest;
import com.vcredit.creditcat.vo.product.RepaymentPlainBizData;
import com.vcredit.creditcat.vo.product.RepaymentPlainItem;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.BeanUtil;
import com.vcredit.framework.util.JacksonUtil;

@Controller
public class ProductRepaymentCallbackController {

	private static final Logger LOG = LoggerFactory.getLogger(ProductRepaymentCallbackController.class);

	// 合作方的公钥（验签用）
	@Value("${request.parent.publicKey}")
	private String publicKey;
	//信用猫的私钥（解密用）
	@Value("${request.xinyongmao.privateKey}")
	private String privateKey;
	
	@Reference(version = "1.0")
	private IRepaymentCallbackManager repaymentCallbackManager;
	
	/**
	 * 接收还款计划
	 * @author zhaoqi01
	 * @param request
	 * @param param
	 * @return
	 * @throws JsonProcessingException
	 */
	@Log
	@RequestMapping("callback/repaymentplan")
	@ResponseBody
	public CommonResultVo<Object> repaymentplanCallback(HttpServletRequest request, @RequestBody CommonProductCreditCallbackParam param) throws JsonProcessingException {
		Long productId = null;
		Long custId = null;
		CommonResultVo<Object> result = new CommonResultVo<Object>();
		try {
			CommonRequest commonRequest = new CommonRequest();
			BeanUtil.copy(param, commonRequest);
			String decryptedData = CommonSecuritUtil.getDecryptedData(commonRequest, publicKey, privateKey);
			LOG.info("------------产品主动还款计划回调参数记录  params{app_id="+param.getApp_id()+","
					+ "biz_data="+ decryptedData +"}");
			RepaymentPlainBizData bizData = JacksonUtil.Json2Obj(decryptedData, new TypeReference<RepaymentPlainBizData>(){});
			productId = (long)(param.getApp_id() - 200000);
			
			repaymentCallbackManager.insertOrUpdateRepaymentplan(productId,this.packageRepaymentplainDto(bizData));
			
			result.setCode(200);
			return result;
		} catch (Exception e) {
			LOG.error("------------产品主动还款计划回调异常  !! productId="+productId+", custId="+custId, e);
			result.setCode(0);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	private RepaymentplainDto packageRepaymentplainDto(RepaymentPlainBizData bizData) {
		RepaymentplainDto repaymentplainDto = new RepaymentplainDto();
		repaymentplainDto.setOrderId(bizData.getOrder_id());
		repaymentplainDto.setTotalAmount(bizData.getTotal_amount());
		repaymentplainDto.setCharge(bizData.getCharge());
		repaymentplainDto.setAlpaid(bizData.getAlpaid());
		repaymentplainDto.setBepaid(bizData.getBepaid());
		repaymentplainDto.setTotalPeriod(bizData.getTotal_period());
		repaymentplainDto.setFinishPeriod(bizData.getFinish_period());
		
		List<RepaymentplainItemDto> list = new ArrayList<RepaymentplainItemDto>();
		for(RepaymentPlainItem item : bizData.getList()) {
			RepaymentplainItemDto dto = new RepaymentplainItemDto();
			dto.setPeriodNo(item.getPeriod_no());
			dto.setDueTime(item.getDue_time());
			dto.setAmount(item.getAmount());
			dto.setOverdueFee(item.getOverdue_fee());
			dto.setBillStatus(item.getBill_status());
			dto.setPayType(item.getPay_type());
			dto.setPrinciple(item.getPrinciple());
			dto.setInterest(item.getInterest());
			dto.setSuccessTime(item.getSuccess_time());
			
			list.add(dto);
		}
		
		repaymentplainDto.setList(list);
		return repaymentplainDto;
	}
	
	/**
	 * 接收还款状态
	 * @author zhaoqi01
	 * @param request
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping("callback/repaymentstatus")
	@ResponseBody
	public CommonResultVo<Object> repaymentstatusCallback(HttpServletRequest request, @RequestBody CommonProductCreditCallbackParam param) throws Exception {
		Long productId = null;
		Long custId = null;
		CommonResultVo<Object> result = new CommonResultVo<Object>();
		CommonRequest commonRequest = new CommonRequest();
		BeanUtil.copy(param, commonRequest);
		String decryptedData = CommonSecuritUtil.getDecryptedData(commonRequest, publicKey, privateKey);
		LOG.info("------------产品还款状态回调参数记录  params{app_id="+param.getApp_id()+","
				+ "biz_data="+ decryptedData +"}");
		return new CommonResultVo<Object>(200,null,null);
	}
}
